package com.zh.harmony.handlerthread;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;


/**
 * HandlerThread，一个有EventRunner的线程
 */
public class HandlerThread extends Thread {
    int mPriority;
    int mTid = -1;
    EventRunner mEventRunner;
    private EventHandler mHandler;

    public HandlerThread(String name) {
        super(name);
        mPriority = Thread.NORM_PRIORITY;
    }

    public HandlerThread(String name, int priority) {
        super(name);
        mPriority = priority;
    }

    protected void onEventRunnerPrepared() {
    }

    @Override
    public void run() {
        mTid = getThreadId();
        //创建轮询器，绑定到当前线程
        EventRunner eventRunner = EventRunner.create(false);
        synchronized (this) {
            mEventRunner = eventRunner;
            notifyAll();
        }
        setPriority(mPriority);
        onEventRunnerPrepared();
        //开始循环
        eventRunner.run();
        mTid = -1;
    }

    /**
     * 获取这个线程的EventRunner
     */
    public EventRunner getEventRunner() {
        if (!isAlive()) {
            return null;
        }
        // If the thread has been started, wait until the looper has been created.
        synchronized (this) {
            while (isAlive() && mEventRunner == null) {
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
        }
        return mEventRunner;
    }

    /**
     * 获取线程绑定的EventHandler
     */
    public EventHandler getThreadHandler() {
        if (mHandler == null) {
            mHandler = new EventHandler(getEventRunner());
        }
        return mHandler;
    }

    /**
     * 退出
     */
    public boolean quit() {
        EventRunner eventRunner = getEventRunner();
        if (eventRunner != null) {
            //结束循环
            eventRunner.stop();
            return true;
        }
        return false;
    }

    /**
     * 获取线程Id
     */
    public int getThreadId() {
        return mTid;
    }
}